<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="search.username"
        v-haspermi="['bxy:user:search']"
        :placeholder="$t('user.username')"
        :maxlength="50"
        clearable
        class="filter-item"
        @blur="trim('username')"
        @mouseout.native="blurRule($event)"
      />
      <el-button
        v-haspermi="['bxy:user:search']"
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="getUser"
      >{{ $t('common.search') }}</el-button>
      <el-button
        v-haspermi="['bxy:user:add']"
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        @click="showAddFormDialog"
      >{{ $t('common.newAdd') }}</el-button>
    </div>

    <el-table
      :data="users"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column
        type="index"
        :label="$t('common.num')"
        align="center"
        width="80"
      />
      <el-table-column
        property="username"
        :label="$t('user.username')"
        align="center"
        width="200"
      />
      <el-table-column :label="$t('user.role')" align="center" width="200">
        <template slot-scope="scope">
          <div>
            {{ getAuthorityText(scope.row) }}
          </div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('user.bindUserInfor')" align="center">
        <template slot-scope="scope">
          <div>
            {{ scope.row.user?((scope.row.user.org&&scope.row.user.org.length>0) ?scope.row.user.org[0].name+'-':'')+scope.row.user.displayName:'' }}
          </div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('common.operate')" align="center" width="300">
        <template slot-scope="scope">
          <el-button
            v-if="isNotSuperman(scope.row)"
            v-haspermi="['bxy:user:resetPwd']"
            icon="el-icon-reset"
            class="oprate"
            size="mini"
            plain
            type="primary"
            @click.native.prevent="resetUserPwd(scope.row)"
          >{{ $t('user.resetUserPwd') }}</el-button>
          <el-button
            v-if="isNotSuperman(scope.row)"
            v-haspermi="['bxy:user:edit']"
            icon="el-icon-reset"
            class="oprate"
            size="mini"
            plain
            type="success"
            @click.native.prevent="editUser(scope.row)"
          >{{ $t('settings.editor') }}</el-button>
          <el-button
            v-if="isNotSuperman(scope.row)"
            v-haspermi="['bxy:user:delete']"
            icon="el-icon-delete"
            class="oprate"
            size="mini"
            plain
            type="danger"
            @click.native.prevent="removeUser(scope.row)"
          >
            {{ $t('common.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="search.page"
      :limit.sync="search.size"
      @pagination="pagination"
    />

    <el-dialog
      :title="userFormTitle"
      :visible.sync="userFormVisible"
      @close="userDialog"
    >
      <el-form
        ref="userForm"
        :rules="rules"
        :model="form"
        label-position="left"
        label-width="110px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item :label="$t('user.username')" prop="username">
          <el-input
            v-model="form.username"
            :placeholder="$t('user.enterUsername')"
            style="width:250px;"
          />
        </el-form-item>
        <el-form-item :label="$t('user.role')" prop="customRoleId">
          <el-select
            v-model="form.customRoleId"
            :placeholder="$t('common.pleaseSelect')"
            style="width:250px;"
          >
            <el-option
              v-for="item in customRoles"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('settings.selectUser')" prop="userId">
          <el-input
            v-model="form.userId"
            style="width:250px;"
            clearable
            @focus="employeeChooseVisible = true"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="userFormVisible = false">
          {{ $t('common.cancel') }}
        </el-button>
        <el-button type="primary" @click="saveUser">
          {{ confirmText }}
        </el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="$t('settings.selectPeople')"
      :visible.sync="employeeChooseVisible"
      width="800px"
      top="10vh"
      class="dialog-people-reset"
    >
      <employee-choose-single
        @confirm="confirmSelect"
        @cancel="cancelSelect"
        @chooseLeader="chooseEmployee"
      />
    </el-dialog>
  </div>
</template>

<script>
import EmployeeChooseSingle from '@/components/employee-form-leader';
import user from '@/api/user';
import * as settings from '@/api/settings';
import Pagination from '@/components/Pagination';
import { trim } from '@/utils/index';

export default {
  name: 'Employee',
  components: { Pagination, EmployeeChooseSingle },
  data() {
    return {
      search: {
        username: null,
        page: 1,
        size: 10,
        role: '',
      },
      users: [],
      total: 0,
      employeeChooseVisible: false,
      form: {
        username: null,
        role: 'ROLE_MANAGER',
        customRoleId: null,
        userId: null,
      },
      id: null,
      userFormVisible: false,
      customRoles: [],
      type: 'createUser',
    };
  },
  computed: {
    userFormTitle() {
      if (this.type === 'createUser') {
        return this.$t('user.createUser');
      } else {
        return this.$t('user.editUser');
      }
    },
    confirmText() {
      if (this.type === 'createUser') {
        return this.$t('common.create');
      } else {
        return this.$t('common.ok');
      }
    },
    rules() {
      const validatePassword = (rule, value, callback) => {
        if (!value) {
          callback(new Error(this.$t('user.enterPassword')));
        } else if (value.length < 6) {
          callback(new Error(this.$t('login.passwordDigits')));
        } else {
          callback();
        }
      };
      return {
        username: [{ required: true, message: this.$t('user.enterUsername'), trigger: 'blur' }],
        customRoleId: [{ required: true, message: this.$t('user.selectCustomRole'), trigger: 'change' }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }],
      };
    },
  },
  created() {
    this.refreshUser();
  },
  methods: {
    isNotSuperman(row) {
      return row.role !== 'ROLE_SUPERMAN';
    },
    resetUserForm() {
      this.form = {
        username: null,
        role: 'ROLE_MANAGER',
        customRoleId: null,
        userId: null,
      };
    },
    /**
     * 路由到添加页面
     */
    showAddFormDialog() {
      this.resetUserForm();
      this.userFormVisible = true;
      this.$nextTick(() => {
        this.$refs['userForm'].clearValidate();
      });
    },
    saveUser() {
      this.$refs['userForm'].validate(async valid => {
        if (valid) {
          await user.saveUser(this.form, this.type, this.id);
          this.$message({
            message: this.$t('user.saveUserSuccess'),
            type: 'success',
          });
          this.userFormVisible = false;
          this.refreshUser();
        }
      });
    },
    /**
     * 重置用户密码
     */
    async resetUserPwd(row) {
      await user.resetPwd(row.id);
      this.$message({
        message: this.$t('user.resetPwdSuccessfully'),
        type: 'success',
      });
    },
    /**
     * 删除用户
     */
    removeUser(row) {
      this.$confirm(this.$t('user.removeUserTips'), this.$t('common.tips'), {
        type: 'warning',
      }).then(async() => {
        await user.removeUser(row.id);
        this.handleCurrentChange(this.search.page);
        this.$message({
          message: this.$t('user.removeSuccessfully'),
          type: 'success',
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: this.$t('user.cancelRemove'),
        });
      });
    },
    // 重新加载用户数据
    refreshUser() {
      this.search.page = 1;
      this.getUser();
    },
    // 获取豆豆用户信息
    async getUser() {
      const res = await user.getUser(this.search);
      this.users = res.data;
      console.log(res);
      this.total = Number(res.headers['x-total-count']);
      this.getCustomRoles();
    },
    pagination() {
      this.getUser();
    },
    handleSizeChange(val) {
      this.search.size = val;
      this.getUser();
    },
    handleCurrentChange(val) {
      this.search.page = val;
      this.getUser();
    },
    getAuthorityText(row) {
      return row.customRole.name;
    },
    /**
     * 获取管理员角色列表
     */
    async getCustomRoles() {
      const res = await settings.getRoles({ page: 1, size: 2000 });
      this.customRoles = res.data;
    },
    /**
     * 确定
     * @param {JSON} user 选择人员单条信息
     */
    confirmSelect(user) {
      this.employeeChooseVisible = false;
      this.form.userId = user.userID;
      this.form.username = user.phoneNum;
      this.form.name = user.name;
    },
    /**
     * 取消选择人员
     */
    cancelSelect() {
      this.employeeChooseVisible = false;
    },
    /**
     * 选择人员
     * @param {JSON} user 人员相关数据信息
     */
    chooseEmployee(user) {
      this.employeeChooseVisible = false;
      this.form.userId = user.id;
    },
    /**
     * 编辑用户
     **/
    editUser(row) {
      this.type = 'editUser';
      const tempObj = Object.assign({}, row);
      this.id = tempObj.id;
      this.form = {
        username: tempObj.username,
        role: tempObj.role,
        customRoleId: tempObj.customRole.id,
        userId: !tempObj.user ? '' : (tempObj.user.id || ''),
      };
      // console.log(this.customRoleId);
      this.userFormVisible = true;
    },
    /**
     * 关闭创建/编辑用户 恢复类型
     **/
    userDialog() {
      this.type = 'createUser';
    },
    /**
     * 去除两端空格处理
     * @param {String} name 输入框名称
     */
    trim(name) {
      this.search[name] = trim(this.search[name]);
    },
    /**
     * 失去焦点
     * @param {DOMEvent} event 当前输入框
     */
    blurRule(event) {
      // 输入框失去焦点操作
      event.target.blur();
    },
  },
};
</script>

<style scoped>
.filter {
  display: flex;
  margin-left: 15px;
  margin-top: 15px;
  color: #333;
  font-size: 14px;
}
.department {
  margin-left: 15px;
}
.el-input {
  width: 250px;
}
.button {
  margin-left: 15px;
}
.table {
  width: 100%;
  margin-left: 10px;
  margin-top: 20px;
}
.pagination {
  margin-top: 20px;
  width: 100%;
  text-align: center;
}
</style>
